package com.jy.datapipeline.importserver.handler;

import com.jy.datapipeline.common.util.BeanFactoryUtil;
import com.jy.datapipeline.importserver.common.enums.impl.TaskStatusEnum;
import com.jy.datapipeline.importserver.entity.ImportTask;
import com.jy.datapipeline.importserver.service.ImportSubTaskService;
import com.jy.datapipeline.importserver.service.ImportTaskService;
import com.jy.datapipeline.importserver.support.QuartzSupport;
import lombok.SneakyThrows;
import org.quartz.*;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

/**
 * @类名 ScheduleTaskUpdStatusHandler
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/4/27 21:26
 * @版本 1.0
 */
public class ScheduleTaskUpdStatusHandler extends QuartzJobBean {

    private final QuartzSupport quartzSupport;

    public ScheduleTaskUpdStatusHandler() {
        this.quartzSupport = BeanFactoryUtil.getBean(QuartzSupport.class);
    }

    @SneakyThrows
    @Override
    protected void executeInternal(JobExecutionContext context) {
        ImportTaskService importTaskService = BeanFactoryUtil.getBean(ImportTaskService.class);
        ImportSubTaskService importSubTaskService = BeanFactoryUtil.getBean(ImportSubTaskService.class);
        Scheduler scheduler = BeanFactoryUtil.getBean(Scheduler.class);

        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String taskId = (String) jobDataMap.get("taskId");
        String jobIdentity = (String) jobDataMap.get("jobIdentity");

        if (!quartzSupport.isPaused(taskId)) {
            Integer exists = importSubTaskService.queryFailSubtask(taskId);
            if (exists == null) {
                ImportTask importTask = new ImportTask();
                importTask.setTaskId(taskId);
                importTask.setUpdateTime(new Date());
                importTask.setTaskStatus(String.valueOf(TaskStatusEnum.SUCCESS.getCode()));
                importTaskService.modifyTaskByTaskId(importTask);
                scheduler.deleteJob(JobKey.jobKey(jobIdentity));
            }
        }
    }
}
